﻿using System;
using System.Device.Location;
using System.IO.IsolatedStorage;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;

namespace WP8_PPS.Services
{
    /// <summary>
    /// Wrapper for the GeoLocator Object which will allow access to One Shot Location
    /// </summary>
    public class GeolocatorService
    {
        #region Constructor
        public GeolocatorService()
        {
        }
        #endregion

        #region Helper Methods
        public async Task<GeoCoordinate> GetOneShotLocationAsync()
        {
            if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true)
            {
                // The user has opted out of Location.
                return null;
            }

            // Create Geolocator with default setting
            Geolocator geolocator = new Geolocator();
            geolocator.DesiredAccuracyInMeters = 50;

            try
            {
                // Trying to access location
                Geoposition geoposition = await geolocator.GetGeopositionAsync();
                // Returning the GeoCoordinate location
                return CreateGeoCoordinate(geoposition.Coordinate);
            }
            catch
            {
                return null;
            }
        }
        public static GeoCoordinate CreateGeoCoordinate(Geocoordinate geocoordinate)
        {
            // Removing all nullable types to values or zero
            GeoCoordinate location = new GeoCoordinate()
            {
                Altitude = (geocoordinate.Altitude.HasValue && !double.IsNaN(geocoordinate.Altitude.Value)) ? geocoordinate.Altitude.Value : 0,
                Course = (geocoordinate.Heading.HasValue && !double.IsNaN(geocoordinate.Heading.Value)) ? geocoordinate.Heading.Value : 0,
                HorizontalAccuracy = geocoordinate.Accuracy,
                Latitude = geocoordinate.Latitude,
                Longitude = geocoordinate.Longitude,
                Speed = (geocoordinate.Speed.HasValue && !double.IsNaN(geocoordinate.Speed.Value)) ? geocoordinate.Speed.Value : 0,
                VerticalAccuracy = (geocoordinate.AltitudeAccuracy.HasValue && !double.IsNaN(geocoordinate.AltitudeAccuracy.Value)) ? geocoordinate.AltitudeAccuracy.Value : 0
            };

            return location;
        }
        #endregion
    }
}
